import { Injectable, Inject } from '@nestjs/common';
import { MinioService } from 'nestjs-minio-client';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class MinioClientService {
  @Inject(MinioService)
  private readonly minioService: MinioService;

  @Inject(ConfigService)
  private readonly configService: ConfigService;

  private bucketName: string;

  constructor(configService: ConfigService) {
    this.bucketName = configService.get('minio.bucket');
  }

  // 根据url链接删除文件
  async deleteMinioFile(urls: string[]) {
    await Promise.all(
      urls.map((url) => {
        const file = url.split('/').slice(4).join('/');
        this.minioService.client.removeObject(this.bucketName, file);
      }),
    );
  }

  // 根据前缀获取文件列表
  async listMinioFiles(prefix: string) {
    const objects = await this.minioService.client.listObjects(
      this.bucketName,
      prefix && prefix + '/',
    );

    const res = new Promise<string[]>((resolve) => {
      const fileNames: string[] = [];

      objects.on('data', (object) => {
        const fileName = object.name;
        fileNames.push(fileName);
      });
      objects.on('end', () => {
        resolve(fileNames);
      });
    });

    return await res;
  }
}
